<!-- 返工出库-编辑 -->
<template>
	<view class="content">
		<!-- 顶部导航栏 -->
		<u-navbar :fixed="false" :title="titleName" :autoBack="true" :safeAreaInsetTop="true" leftIconColor="#fff">
			<view slot="right" @click="openScan">
				<uni-icons v-if="!$utils.isPda()" type="scan" size="24" color="#fff"></uni-icons>
			</view>
		</u-navbar>

		<!-- 表头信息 -->
		<view class="headTabWrap">
			<uni-segmented-control :current="currenTabIndex" :values="items" style-type="text" active-color="#51d0d0"
				@clickItem="onClickItem" />
			<view class="panelBtn" @click="togglePanel()">
				<uni-icons v-if="currenTabIndex==null" type="eye" size="24" color="#51D0D0"></uni-icons>
				<uni-icons v-else type="eye-slash" size="24" color="#8A8A8A"></uni-icons>
			</view>
		</view>

		<view class="headTabContent">
			<view v-show="currenTabIndex === 0">
				<u--form labelPosition="left" :model="formData" labelWidth="80">
					<u-form-item prop="FCode" borderBottom>
						<view class="item-label">
							<uni-icons fontFamily="CustomFontPlatform" :size="20"
								color="#808080">{{$utils.toUniCode('&#xed1c;')}}</uni-icons>
							<text class="label-text">单据编号</text>
						</view>
						<u--input :value="formData.FCode" disabled disabledColor="#fff" placeholder="自动生成"
							border="none"></u--input>
					</u-form-item>
					<u-form-item prop="FDate" borderBottom>
						<view class="item-label">
							<uni-icons fontFamily="CustomFontPlatform" :size="20"
								color="#808080">{{$utils.toUniCode('&#xe7ac;')}}</uni-icons>
							<text class="label-text">单据日期</text>
						</view>
						<u--input :value="formData.FDate" disabled disabledColor="#fff" placeholder="单据日期"
							border="none"></u--input>
					</u-form-item>
					<u-form-item prop="BillNO" borderBottom>
						<view class="item-label">
							<uni-icons fontFamily="CustomFontPlatform" :size="20"
								color="#808080">{{$utils.toUniCode('&#xed21;')}}</uni-icons>
							<text class="label-text">工单编号</text>
							<text class="required">*</text>
						</view>
						<u--input :value="formData.BillNO" disabled disabledColor="#fff" placeholder="请扫描工单"
							border="none"></u--input>
						<uni-icons v-if="!$utils.isPda()" type="scan" size="22" color="#51d0d0"
							@click="rowOpenScan"></uni-icons>
					</u-form-item>
					<u-form-item prop="FWorkshopName" borderBottom>
						<view class="item-label">
							<uni-icons fontFamily="CustomFontPlatform" :size="20"
								color="#808080">{{$utils.toUniCode('&#xe72a;')}}</uni-icons>
							<text class="label-text">返工车间</text>
							<text class="required">*</text>
						</view>
						<u--input :value="formData.FWorkshopName" disabled disabledColor="#fff" placeholder="由工单带出"
							border="none"></u--input>
					</u-form-item>
				</u--form>
			</view>
			<view v-show="currenTabIndex === 1">
				<u--form labelPosition="left" :model="formData" labelWidth="80">
					<u-form-item prop="FWarehouseName" borderBottom @click="openBaseScreen('仓库')">
						<view class="item-label">
							<uni-icons fontFamily="CustomFontPlatform" :size="20"
								color="#808080">{{$utils.toUniCode('&#xe689;')}}</uni-icons>
							<text class="label-text">出库仓库</text>
							<text class="required">*</text>
						</view>
						<u--input :value="formData.FWarehouseName" disabled disabledColor="#fff" placeholder="请选择出库仓库"
							border="none"></u--input>
						<u-icon slot="right" name="arrow-right"></u-icon>
					</u-form-item>
					<u-form-item prop="FStorageCode" borderBottom @click="openBaseScreen('库位')">
						<view class="item-label">
							<uni-icons fontFamily="CustomFontPlatform" :size="20"
								color="#808080">{{$utils.toUniCode('&#xeb44;')}}</uni-icons>
							<text class="label-text">出库库位</text>
							<text class="required">*</text>
						</view>
						<u--input :value="formData.FStorageCode" disabled disabledColor="#fff" placeholder="请选择出库库位"
							border="none"></u--input>
						<u-icon slot="right" name="arrow-right"></u-icon>
					</u-form-item>
					<u-form-item borderBottom>
						<view class="item-label">
							<uni-icons fontFamily="CustomFontPlatform" :size="20"
								color="#808080">{{$utils.toUniCode('&#xe713;')}}</uni-icons>
							<text class="label-text">出库数量</text>
							<text class="required">*</text>
						</view>
						<u--input type="digit" v-model="currentNum" placeholder="请输入出库数量" clearable
							border="none"></u--input>
					</u-form-item>
				</u--form>
			</view>
		</view>

		<!-- 子表信息 -->
		<view class="detail">
			<!-- 子表页签 -->
			<view class="detail-label">
				<view :class="tabIndex==1?'on':''" @click="tabIndex = 1;">出库明细</view>
				<view :class="tabIndex==2?'on':''" @click="tabIndex = 2;">返工明细</view>
			</view>

			<!-- 出库明细 -->
			<view v-show="tabIndex==1">
				<u-empty v-show="!formDetail.length" icon="/static/image/Img/DataEmpty.png" :style="{height:srvHeight}"
					text="暂无出库明细"></u-empty>
				<scroll-view v-show="formDetail.length" class="rowContainer" :style="{height:srvHeight}"
					:scroll-y="true" :scroll-with-animation="true" :scroll-into-view="'section'+scanRow">
					<view :id="'section'+index" class="productRow" :class="scanRow==index ? 'b-p' : 'b-p-t'"
						v-for="(row,index) in formDetail" @click="setScanRow(index)">
						<view class="productRow-title">
							<view style="flex: 1;">【{{index+1}}】{{row.ProductName}}</view>
						</view>
						<view class="productRow-main">
							<view class="total-wrap">
								<text class="total-label">
									账面库存:
								</text>
								<text class="total-value">
									{{row.InventoryQty}}
								</text>
							</view>
							<view class="total-wrap">
								<text class="total-label">
									库存单位:
								</text>
								<text class="total-value">
									{{row.UnitName}}
								</text>
							</view>
						</view>
						<view class="productRow-main">
							<view class="total-wrap">
								<text class="total-label">
									可领数量:
								</text>
								<text class="total-value">
									{{row.SYQty}}
								</text>
							</view>
							<view class="total-wrap">
								<text class="total-label">
									扫码合计:
								</text>
								<text class="total-value">
									{{row.scannedQty}}
								</text>
							</view>
						</view>
						<view class="productRow-main">
							<text v-if="!formData.Approve" class="del-title">删除</text>
							<text class="batch-title">仓库</text>
							<text class="pos-title">库位</text>
							<text class="qty-title">数量</text>
						</view>

						<view v-for="(item,itemIndex) in row.batchCodeArray" class="productRow-subWrap">
							<view class="productRow-sub">
								<view v-if="!formData.Approve" @click.stop="deleteCode(row, item, index, itemIndex)"
									class="del-content">
									<uni-icons fontFamily="CustomFontPlatform" :size="16"
										color="#c0392b">{{$utils.toUniCode('&#xeaaa;')}}</uni-icons>
								</view>
								<view class="batch-title">{{item.FWarehouseName}}</view>
								<view class="pos-content">
									{{item.posname}}
								</view>
								<view class="qty-content" @click.stop="showChange(row,index,item,itemIndex)">
									<text style="color: #666;">{{item.qty}}</text>
								</view>
							</view>
							<view class="productRow-main">
								<view class="total-wrap">
									<text class="total-label">
										批次:
									</text>
									<text class="total-value">
										{{item.batch}}
									</text>
								</view>
							</view>
						</view>
					</view>
				</scroll-view>
			</view>

			<!-- 返工明细 -->
			<view v-show="tabIndex==2">
				<view>
					<u-empty v-show="!sourceDetail.length" icon="/static/image/Img/DataEmpty.png"
						:style="{height:srvHeight}" text="暂无返工明细"></u-empty>
					<m-table v-show="sourceDetail.length" ref="table" :height="srvHeight" :headers="headers"
						:contents="sourceDetail" :font-size="[$utils.px2rpx(12)]" :first-line-fixed="true"
						first-col-bg-color="#fff"></m-table>
				</view>
			</view>
		</view>

		<!-- 底部按钮 -->
		<view class="bottom" :style="$utils.disposeSafeBottomFun()">
			<u-button v-if="!formData.Approve" size="small" color="#51d0d0" :disabled="ifConfirm" :loading="ifConfirm"
				@click="confirmSubmit">保存单据</u-button>
			<u-button v-if="!formData.Approve && formData.FStockID" size="small" color="#c0392b" :disabled="ifConfirm"
				:loading="ifConfirm" @click="confirmApprove">审核</u-button>
			<u-button v-if="formData.Approve" size="small" color="#c0392b" :disabled="ifConfirm" :loading="ifConfirm"
				@click="approveFunction">取消审核</u-button>
		</view>

		<!-- 子表数值修改弹窗 -->
		<u-modal :show="showChangePanel" :showCancelButton="true" :closeOnClickOverlay="true" confirmColor="#51d0d0"
			:duration="0" title="数量修改" @confirm="confirmChange" @cancel="cancelChange" @close="closeChange">
			<!-- <u--input ref="input" type="digit" v-model="newValue" focus fontSize="20px" color="#666666" border="none"
				clearable placeholder="请输入修改数量"></u--input> -->
			<!-- 适配低性能设备输入框 -->
			<input ref="input" type="digit" v-model="newValue" focus fontSize="20px" color="#666666" border="none"
				clearable placeholder="请输入修改数量"></input>
		</u-modal>

		<!-- PDA扫码 -->
		<m-pda-scancode v-if="$utils.isPda()" listenName="BatchEditScan"
			:SetContent="{action:$store.state.systemConfig.sysDeviceInfo.broadcastAction,extra:$store.state.systemConfig.sysDeviceInfo.broadcastResult}"></m-pda-scancode>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				titleName: '',
				currenTabIndex: 0, // 表头tab当前index
				items: ['基本项', '扫码项'], //	表头tab名称
				scanDisabled: false,
				ifConfirm: false,
				showChangePanel: false,
				isFocused: false,
				currentNum: '', // 本次数量
				scanRow: 0, // 当前扫码行
				headTabWrapHeight: 0, //	表头tab容器高度
				headTabContentHeight: 0, //	表头tab内容高度
				detailLabelHeight: 0, // 切换标签高度
				bottomHeight: 0, // 底部按钮高度
				srvHeight: 'auto', // scrollview高度
				oldValue: '',
				newValue: '',
				posRow: 0,
				posIdx: 0,
				formData: {
					FStockID: 0,
					FCode: '',
					FDate: '',
					FWarehouseID: 0,
					FWarehouseName: '',
					FWorkshopID: 0,
					FWorkshopName: '',
					FStorageID: 0,
					FStorageCode: '',
					BillNO: '',
					Approve: 0
				},
				tabIndex: 1, // 子表页签
				formDetail: [],
				sourceDetail: [],
				headers: [{
						label: '序号',
						key: 'seq',
						width: 100
					},
					{
						label: '物料名称',
						key: 'ProductName',
						width: 360
					},
					{
						label: '单位',
						key: 'UnitName',
						width: 180
					},
					{
						label: '应领数量',
						key: 'NeedQty',
						width: 180
					},
					{
						label: '已领数量',
						key: 'ReQty',
						width: 180
					},
					{
						label: '可领数量',
						key: 'SYQty',
						width: 180
					}
				]
			}
		},

		created() {

		},

		mounted() {
			let that = this;

			// 监听下拉回调
			uni.$on('BatchEditChoice', function(ret) {
				let selectItem = ret.data;

				if (ret.type == '仓库') {
					if (selectItem.FWarehouseID != that.formData.FWarehouseID) {
						that.formData.FWarehouseID = selectItem.FWarehouseID;
						that.formData.FWarehouseName = selectItem.FWarehouseName;

						// 仓库变更-库位清空
						that.formData.FStorageID = 0;
						that.formData.FStorageCode = '';
					}
				}
				if (ret.type == '车间') {
					that.formData.FWorkshopID = selectItem.FWorkshopID;
					that.formData.FWorkshopName = selectItem.FWorkshopName;
				}
				if (ret.type == '库位') {
					that.formData.FStorageID = selectItem.FStorageID;
					that.formData.FStorageCode = selectItem.FStorageCode;
				}
				if (ret.type == '子表库位') {
					let matchItem = that.formDetail[that.posRow].batchCodeArray[that.posIdx];
					matchItem.posid = selectItem.FStorageID;
					matchItem.posname = selectItem.FStorageCode;
				}
			})

			// PDA扫码处理
			uni.$on('BatchEditScan', function(content) {
				let scanData = that.$utils.wmsFun.scanTransf(content);
				that.scanHandler(scanData);
			})

			// 动态计算元素高度
			that.getElementHeights();
		},

		methods: {

			// 显示隐藏面板
			togglePanel() {
				if (this.currenTabIndex == null) {
					this.currenTabIndex = 0;
				} else {
					this.currenTabIndex = null;
				}
				this.changeTabContentHeight();
			},

			// 切换表单面板
			onClickItem(e) {
				if (this.currenTabIndex != e.currentIndex) {
					this.currenTabIndex = e.currentIndex;
					this.changeTabContentHeight();
				}
			},

			changeTabContentHeight() {
				const query = uni.createSelectorQuery().in(this);
				this.$nextTick(() => {
					query.select('.headTabContent').boundingClientRect(rect => {
						this.headTabContentHeight = rect.height;
						console.log(this.headTabContentHeight);
						this.calcSrvHeight(this.headTabContentHeight);

					}).exec();
				})
			},

			// 获取单据详情
			getPageData() {
				let that = this;
				that.Request.request('batchCode_cktlDtl', {
						FStockID: that.formData.FStockID
					}, function(res) {
						let data = res.data;

						// 1.初始化表头信息
						that.formData.FDate = data.ds[0].FDate;
						that.formData.FCode = data.ds[0].FCode;
						that.formData.FWorkshopID = data.ds[0].FWorkshopID;
						that.formData.FWorkshopName = data.ds[0].FWorkshopName;
						that.formData.BillNO = data.ds[0].BillNO;
						that.formData.Approve = data.ds[0].Approve;

						// 2.初始化批次码出库明细
						var formDetail = [];
						for (var i in data.ds1) {
							var x = 0;
							for (var j in formDetail) {
								if (formDetail[j].ProductID == data.ds1[i].ProductID && formDetail[j]
									.WoPartID == data.ds1[i].WoPartID) {
									x = 1;
									formDetail[j].batchCodeArray.push({
										FStockDeID: data.ds1[i].FStockDeID,
										batch: data.ds1[i].FBatchNo,
										qty: data.ds1[i].FQty,
										FWarehouseID: data.ds1[i].FWarehouseID,
										FWarehouseName: data.ds1[i].FWarehouseName,
										posid: data.ds1[i].FStorageID,
										posname: data.ds1[i].FStorageCode
									})
								}
							}

							if (x == 0) {
								if (data.ds1[i].FQty == 0) {
									formDetail.push({
										ProductID: data.ds1[i].ProductID,
										ProductCode: data.ds1[i].ProductCode,
										ProductName: data.ds1[i].ProductName,
										WoOrderID: data.ds1[i].WoOrderID,
										WoPartID: data.ds1[i].WoPartID,
										NeedQty: data.ds1[i].NeedQty,
										ReQty: data.ds1[i].ReQty,
										SYQty: data.ds1[i].SYQty,
										InventoryQty: data.ds1[i].InventoryQty,
										UnitName: data.ds1[i].UnitName,
										scannedQty: 0,
										batchCodeArray: []
									})
								} else {
									formDetail.push({
										ProductID: data.ds1[i].ProductID,
										ProductCode: data.ds1[i].ProductCode,
										ProductName: data.ds1[i].ProductName,
										WoOrderID: data.ds1[i].WoOrderID,
										WoPartID: data.ds1[i].WoPartID,
										NeedQty: data.ds1[i].NeedQty,
										ReQty: data.ds1[i].ReQty,
										SYQty: data.ds1[i].SYQty,
										InventoryQty: data.ds1[i].InventoryQty,
										UnitName: data.ds1[i].UnitName,
										scannedQty: 0,
										batchCodeArray: [{
											FStockDeID: data.ds1[i].FStockDeID,
											batch: data.ds1[i].FBatchNo,
											qty: data.ds1[i].FQty,
											FWarehouseID: data.ds1[i].FWarehouseID,
											FWarehouseName: data.ds1[i].FWarehouseName,
											posid: data.ds1[i].FStorageID,
											posname: data.ds1[i].FStorageCode
										}]
									})
								}
							}
						}
						formDetail.forEach((row, index) => that.calcRowTotal(row, index));
						that.formDetail = formDetail;

						that.sourceDetail = data.ds2.map((item, index) => ({
							...item,
							seq: index + 1
						}));
					},
					function(err) {}, that.Request.IPAgreement() + that.Request.serverIP() +
					'/Frame/SqlData', 1)
			},

			// 保存单据
			confirmSubmit(index) {
				let that = this;


				let isEmpty = that.formDetail.every(item => item.scannedQty == 0);
				if (isEmpty) {
					that.$utils.msg('出库明细不能为空!');
					return false;
				} else {
					let FWoPartIDs = [],
						FProductCodes = [],
						FWarehouseIDs = [],
						FStorageIDs = [],
						FBatchNos = [],
						FQtys = []

					for (let i = 0; i < that.formDetail.length; i++) {
						let row = that.formDetail[i];

						for (let j = 0; j < row.batchCodeArray.length; j++) {
							let batchCode = row.batchCodeArray[j];

							FWoPartIDs.push(row.WoPartID);
							FProductCodes.push(row.ProductCode);
							FWarehouseIDs.push(batchCode.FWarehouseID);
							FStorageIDs.push(batchCode.posid);
							FBatchNos.push(batchCode.batch);
							FQtys.push(batchCode.qty);
						}
					}
					let obj = {
						FStockID: that.formData.FStockID,
						FWorkshopID: that.formData.FWorkshopID,
						FWoPartIDs: FWoPartIDs.join(','),
						FProductCodes: FProductCodes.join(','),
						FWarehouseIDs: FWarehouseIDs.join(','),
						FStorageIDs: FStorageIDs.join(','),
						FBatchNos: FBatchNos.join(','),
						FQtys: FQtys.join(',')
					}

					if (index == 1) {
						that.saveFunction(obj, index);
					} else {
						uni.showModal({
							title: '提示',
							content: '是否保存当前单据',
							success: function(res) {
								if (res.confirm) {
									that.saveFunction(obj, index);
								} else if (res.cancel) {
									// console.log('用户点击取消');
								}
							}
						})
					}
				}
			},

			saveFunction(obj, index) {
				let that = this;

				that.Request.request(that.formData.FStockID == 0 ? 'batchCode_cktlAdd' :
					'batchCode_cktlEdit', obj,
					function(res) {
						let data = res.data;

						if (data.ds[0].status == 500) {
							uni.showModal({
								title: '提示',
								content: data.ds[0].msg,
								showCancel: false,
								confirmText: '确定',
								success: (res) => {
									if (res.confirm) {
										// console.log('用户点击确定');
									} else if (res.cancel) {
										// console.log('用户点击取消');
									}
								},
							});
						} else {
							if (that.formData.FStockID == 0) {
								that.formData.FStockID = data.ds[0].FStockID;
								if (index != 1) {
									that.$utils.msg('保存成功!');
								}
							} else {
								if (index != 1) {
									that.$utils.msg('修改成功!');
								}
							}
							that.getPageData();
							if (index == 1) {
								that.approveFunction();
							}
							uni.$emit('BatchListRefresh')
						}

					},
					function(err) {}, that.Request.IPAgreement() + that.Request.serverIP() +
					'/Frame/SqlData', 1)
			},

			// 单据审核
			confirmApprove() {
				let that = this;
				that.confirmSubmit(1);
			},

			// 审核单据
			approveFunction() {
				let that = this;
				let obj = {
					FStockID: that.formData.FStockID,
					isApprove: that.formData.Approve
				};

				let contentStr = '';
				if (that.formData.Approve == 0) {
					contentStr = '是否提交审核?';
				} else if (that.formData.Approve == 1) {
					contentStr = '是否取消审核?'
				}

				uni.showModal({
					title: '提示',
					content: contentStr,
					success: function(res) {
						if (res.confirm) {
							that.Request.request('batchCode_cktlApprove', obj,
								function(res) {
									let data = res.data;
									if (data.ds[0].status == 500) {
										uni.showModal({
											title: '提示',
											content: data.ds[0].msg,
											showCancel: false,
											confirmText: '确定',
											success: (res) => {
												if (res.confirm) {
													// console.log('用户点击确定');
												} else if (res.cancel) {
													// console.log('用户点击取消');
												}
											},
										});
									} else {
										if (that.formData.Approve == 0) {
											that.$utils.msg('审核成功!');
										} else {
											that.$utils.msg('取消审核成功!');
										}
										that.getPageData();
										uni.$emit('BatchListRefresh')
									}
								},
								function(err) {}, that.Request.IPAgreement() + that.Request
								.serverIP() +
								'/Frame/SqlData', 1)
						} else if (res.cancel) {
							// console.log('用户点击取消');
						}
					}
				});

			},

			// 设置扫码物料行
			setScanRow(index) {
				this.scanRow = index;
			},

			// 删除物料批次条码
			deleteCode(row, item, index, itemIndex) {
				let that = this;
				uni.showModal({
					title: '提示',
					content: '确认删除仓库: ' + item.FWarehouseName + ' 库位: ' + item.posname + ' 批次: ' + item.batch +
						'的记录?',
					success: function(res) {
						if (res.confirm) {
							row.batchCodeArray.splice(itemIndex, 1);
							that.calcRowTotal(row, index);
							that.$utils.msg('批次条码删除成功!');
						} else if (res.cancel) {
							console.log('用户点击取消');
						}
					}
				});
			},

			showChange(row, index, item, itemIndex) {
				if (!this.formData.Approve) {
					this.showChangePanel = true;
					this.isFocused = true;
					this.oldValue = item.qty;
					this.newValue = item.qty;
					this.posRow = index;
					this.posIdx = itemIndex;
				}
			},

			confirmChange() {
				var value = this.newValue;

				if (!value) {
					this.$utils.msg('数量不能为零或空!');
				} else {
					let row = this.formDetail[this.posRow];
					let item = row.batchCodeArray[this.posIdx];

					let total = row.scannedQty - this.oldValue + Number(value);
					if (total > row.SYQty) {
						this.$utils.msg('超过可出数量!');
					} else {
						if (Number(value) != this.oldValue) {
							this.$utils.msg('数量修改成功!');
						}
						item.qty = Number(value);
						this.calcRowTotal(row, this.posRow);
					}
				}

				this.showChangePanel = false;
				this.isFocused = false;
			},

			cancelChange() {
				this.showChangePanel = false;
				this.isFocused = false;
			},

			closeChange() {
				this.showChangePanel = false;
				this.isFocused = false;
			},

			// 更改出库明细库位
			changePosition(index, itemIndex) {
				this.posRow = index;
				this.posIdx = itemIndex;
				this.openBaseScreen('子表库位');
			},

			// 计算合计扫码数量
			calcRowTotal(row, index) {
				const totalValue = row.batchCodeArray.reduce((acc, item) => acc + Number(item.qty), 0);
				row.scannedQty = totalValue;
			},

			// 打开摄像头
			openScan() {
				let that = this;
				this.$scanPopup.openScan({
					onlyFromCamera: true,
					scanType: ['qrCode'],
					success: (res) => {
						let scanData = that.$utils.wmsFun.scanTransf(res.result);
						that.scanHandler(scanData);
					}
				})
				/* uni.scanCode({
					onlyFromCamera: true,
					scanType: ['qrCode'],
					success: function(res) {
						let scanData = that.$utils.wmsFun.scanTransf(res.result);
						that.scanHandler(scanData);
					}
				}) */
			},

			rowOpenScan() {
				this.openScan();
			},

			// 扫码处理
			scanHandler(scanData) {
				let that = this;

				if (that.scanDisabled) {
					that.$utils.msg('数据提交中,请稍后再试!');
					return false;
				}
				if (!scanData) {
					that.$utils.msg('请扫描正确的条码!');
					return false;
				}

				if (scanData.type == '工单') {

					if (that.formData.Approve) {
						that.$utils.msg('单据已审核!');
						return false;
					}

					let obj = {
						WoOrderID: scanData.data.code
					}

					that.scanDisabled = true;
					that.Request.request('batchCode_cktlSource', obj, function(res) {
							that.scanDisabled = false;
							let data = res.data;

							if (data.ds[0].status == 500) {
								that.$utils.msg(data.ds[0].msg)
							} else {
								// 初始化主表信息
								that.formData.BillNO = data.ds[0].BillNO;
								that.formData.FWorkshopID = data.ds[0].FWorkshopID;
								that.formData.FWorkshopName = data.ds[0].FWorkshopName;

								that.sourceDetail = data.ds.map((item, index) => ({
									...item,
									seq: index + 1
								}));
								that.formDetail = data.ds.map((item, index) => ({
									...item,
									scannedQty: 0,
									batchCodeArray: []
								}));
								// 切换至领料明细tab
								that.tabIndex = 2;
								that.currenTabIndex = 1;
							}
						}, function(err) {
							that.scanDisabled = false;
						}, that.Request.IPAgreement() + that.Request.serverIP() +
						'/Frame/SqlData', 1)

				} else if (scanData.type == '产品批次码') {

					if (!that.formData.BillNO) {
						that.currenTabIndex = 0;

						that.$utils.msg('请扫描来源单据!')
						return false;
					}

					if (!that.formData.FWarehouseID) {
						that.currenTabIndex = 1;

						that.$utils.msg('请选择出库仓库!')
						return false;
					}

					if (!that.formData.FStorageCode) {
						that.currenTabIndex = 1;

						that.$utils.msg('请选择出库库位!')
						return false;
					}

					if (!that.currentNum) {
						that.currenTabIndex = 1;

						that.$utils.msg('请输入出库数量!')
						return false;
					}

					that.tabIndex = 1;

					// 物料批次信息
					let productInfo = {
						productCode: scanData.data.code,
						batch: scanData.data.batch,
						posid: that.formData.FStorageID,
						posname: that.formData.FStorageCode
					}

					let flag = that.formDetail.some(item => item.ProductCode == productInfo.productCode);
					if (!flag) {
						that.$utils.msg('领料明细不存在当前物料!')
						return false;
					}

					that.scanDisabled = true;
					// 当前选中物料行
					var matchRow = that.formDetail[that.scanRow];
					var matchIndex = that.scanRow;
					var rowChange = false;

					// 批次条码信息
					var batchCode = {
						FStockDeID: 0,
						batch: productInfo.batch,
						qty: Number(that.currentNum),
						FWarehouseID: that.formData.FWarehouseID,
						FWarehouseName: that.formData.FWarehouseName,
						posid: that.formData.FStorageID,
						posname: that.formData.FStorageCode
					}

					let valParams = {
						FWarehouseID: that.formData.FWarehouseID,
						FStorageCode: that.formData.FStorageCode,
						ProductCode: scanData.data.code,
						FBatchNo: scanData.data.batch
					}
					// 验证批次条码库存信息
					that.Request.request('batchCode_cktlYz', valParams, function(res) {
							that.scanDisabled = false;
							let data = res.data;
							if (data.ds[0].status == 500) {
								that.$utils.msg(data.ds[0].msg);
							} else {
								// 判断当前选中行是否跟批次条码物料编码一致
								if (matchRow.ProductCode != productInfo.productCode) {
									let index = that.formDetail.findIndex(item => item.ProductCode == productInfo
										.productCode &&
										item.SYQty > 0);
									if (matchIndex != index) {
										rowChange = true;
										matchIndex = index;
									}
									matchRow = that.formDetail.find(item => item.ProductCode == productInfo
										.productCode && item
										.SYQty >
										0);
								}

								// 存在未出完行
								if (matchRow != undefined) {
									// 本次出库数量大于可出数量,自动改为可出数量
									if ((batchCode.qty + matchRow.scannedQty) > matchRow.SYQty) {
										that.scanDisabled = false;
										that.$utils.msg('超过可领数量!');
										return false;
									}

									if (batchCode.qty > 0) {
										// 插入本次出库信息
										matchRow.batchCodeArray.unshift(batchCode);
										// 匹配行非当前选中行-执行设置和滚动
										if (rowChange) {
											// 设置选中行
											that.setScanRow(matchIndex);
										}
										// 计算扫码合计
										that.calcRowTotal(matchRow, matchIndex);
									} else {
										that.$utils.msg('当前物料已经全部领完!')
										// return false;
									}
								} else {
									that.$utils.msg('当前物料已经全部领完!')
									// return false;
								}
								that.scanDisabled = false;
							}
						}, function(err) {
							that.scanDisabled = false;
						}, that.Request.IPAgreement() + that.Request.serverIP() +
						'/Frame/SqlData', 1)

				} else if (scanData.type == '库位') {

					let obj = {
						QrQZ: scanData.data.tag,
						QrCode: scanData.data.code,
						FWarehouseID: that.formData.FWarehouseID
					}

					that.scanDisabled = true;
					that.Request.request('Get_QrStorage', obj, function(res) {
							that.scanDisabled = false;

							let data = res.data;
							if (data.ds[0].status == 500) {
								that.$utils.msg(data.ds[0].msg)
							} else {
								that.formData.FStorageID = data.ds[0].FStorageID;
								that.formData.FStorageCode = data.ds[0].FStorageCode;

								that.formData.FWarehouseID = data.ds[0].FWarehouseID;
								that.formData.FWarehouseName = data.ds[0].FWarehouseName;
							}
						}, function(err) {
							that.scanDisabled = false;
						}, that.Request.IPAgreement() + that.Request.serverIP() +
						'/Frame/SqlData', 1)

				}
			},

			// 获取相关元素高度
			getElementHeights() {
				this.$nextTick(() => {
					const query = uni.createSelectorQuery().in(this);
					const promises = [];
					// 获取每个元素的高度，并返回一个 Promise
					const getHeightPromise = (selector) => {
						return new Promise((resolve) => {
							query.select(selector).boundingClientRect((rect) => {
								resolve(rect.height);
							}).exec();
						});
					};

					promises.push(getHeightPromise('.headTabWrap'));
					promises.push(getHeightPromise('.headTabContent'));
					promises.push(getHeightPromise('.detail-label'));
					promises.push(getHeightPromise('.bottom'));

					// 等待所有 Promise 完成
					Promise.all(promises).then((heights) => {
						console.log(heights);
						this.headTabWrapHeight = heights[0];
						this.headTabContentHeight = heights[1];
						this.detailLabelHeight = heights[2];
						this.bottomHeight = heights[3];

						this.calcSrvHeight(this.headTabContentHeight);
					});
				})
			},

			// 重新计算scrollview高度
			calcSrvHeight(headTabContentHeight) {
				let safeAreaTop = this.$u.sys().statusBarHeight;
				let height =
					`calc(100vh - 44px - ${safeAreaTop}px - ${this.headTabWrapHeight}px - ${headTabContentHeight}px - ${this.detailLabelHeight}px - ${this.bottomHeight}px)`;
				this.srvHeight = height;
				console.log(this.srvHeight);
			},

			// 公共下拉选择
			openBaseScreen(str) {
				let url = '/commonPage/Tool/baseScreen';
				let obj;

				if (str == '仓库') {
					obj = {
						allowClear: false,
						cmd: 'Droplist_Warehouse',
						type: str,
						ListeningName: 'BatchEditChoice',
						refresherEnabled: false,
						serverSearch: {
							isPaging: false, //是否分页
							showText: 'FWarehouseName', //查询结果显示的字段
							ChoiceDataKey: 'FWarehouseID',
							ChoiceDataData: this.formData.FWarehouseID
						},
						param: {

						}
					}
				}

				if (str == '车间') {
					obj = {
						allowClear: false,
						cmd: 'Droplist_Workshop',
						type: str,
						ListeningName: 'BatchEditChoice',
						refresherEnabled: false,
						serverSearch: {
							isPaging: false, //是否分页
							searchKey: 'FWorkshopName',
							showText: 'FWorkshopName', //查询结果显示的字段
							ChoiceDataKey: 'FWorkshopID',
							ChoiceDataData: this.formData.FWorkshopID
						},
						param: {

						}
					}
				}

				if (str == '库位') {
					if (!this.formData.FWarehouseID) {
						this.$utils.msg('请先选择出库仓库!');
						return false;
					}

					obj = {
						allowClear: false,
						cmd: 'Droplist_Storage',
						type: str,
						ListeningName: 'BatchEditChoice',
						refresherEnabled: false,
						serverSearch: {
							isPaging: false, //是否分页
							searchKey: 'FStorageCode',
							showText: 'FStorageCode', //查询结果显示的字段
							ChoiceDataKey: 'FStorageID',
							ChoiceDataData: this.formData.FStorageID
						},
						param: {
							FWarehouseID: this.formData.FWarehouseID
						}
					}
				}

				if (str == '子表库位') {
					obj = {
						allowClear: false,
						cmd: 'Droplist_Storage',
						type: str,
						ListeningName: 'BatchEditChoice',
						refresherEnabled: false,
						serverSearch: {
							isPaging: false, //是否分页
							searchKey: 'FStorageCode',
							showText: 'FStorageCode', //查询结果显示的字段
							ChoiceDataKey: 'FStorageID',
							ChoiceDataData: this.formDetail[this.posRow].batchCodeArray[this.posIdx].posid
						},
						param: {
							FWarehouseID: this.formData.FWarehouseID
						}
					}
				}

				this.$store.commit('ChangeAndSetStateData', {
					Name1: 'BaseScreenParm',
					data: obj
				})

				uni.navigateTo({
					url: url
				})
			}
		},

		onLoad(option) {
			let menuName = decodeURIComponent(option.menuName);
			this.titleName = menuName + '详情';
			this.formData.FStockID = parseInt(option.FStockID);

			if (this.formData.FStockID != 0) {
				this.getPageData();
			}
		},

		onUnload() {
			uni.$off('BatchEditChoice');
			uni.$off('BatchEditScan');
		}
	}
</script>

<style lang="scss" scoped>
	@import "@/static/assets/scss/wms.scss";
</style>